package com.auto.survey.activity.bluetooth

import android.Manifest
import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresPermission
import com.auto.survey.widget.CentreToast

/**
 * 经典蓝牙管理工具类（移除BLE功能）
 */
class BluetoothManagerUtil private constructor(private val context: Context) {
    // 是否显示未知设备（默认不显示）
    private var showUnknownDevices = false
    // 设备列表和回调
    private val scannedDevices = mutableListOf<BluetoothDevice>()
    // 已配对设备列表
    private val pairedDevices = mutableListOf<BluetoothDevice>()

    private var scanCallback: ((List<BluetoothDevice>) -> Unit)? = null
    private var pairedDevicesCallback: ((List<BluetoothDevice>) -> Unit)? = null

    private var bluetoothService: BluetoothService? = null

    private val handler = Handler(Looper.getMainLooper())

    private var isBound = false

    // 单例实现
    companion object {
        @Volatile
        private var instance: BluetoothManagerUtil? = null

        fun getInstance(context: Context): BluetoothManagerUtil {
            return instance ?: synchronized(this) {
                instance ?: BluetoothManagerUtil(context.applicationContext).also {
                    instance = it
                }
            }
        }
    }

    // Service连接回调
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            val binder = service as BluetoothService.LocalBinder
            bluetoothService = binder.service
            isBound = true
            Log.d("BluetoothManagerUtil", "Service已连接")
        }

        override fun onServiceDisconnected(name: ComponentName) {
            isBound = false
            bluetoothService = null
            Log.d("BluetoothManagerUtil", "Service已断开")
        }
    }

    // 绑定Service
    fun bindService() {
        if (!isBound) {
            val intent = Intent(context, BluetoothService::class.java)
            if (context.packageManager.queryIntentServices(intent, 0).isNotEmpty()) {
                try {
                    // 启动 Service 以确保它在后台运行
                    context.startService(intent)

                    // 绑定 Service
                    val bound = context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
                    Log.d("BluetoothManagerUtil", "尝试绑定Service: $bound")
                } catch (e: Exception) {
                    Log.e("BluetoothManagerUtil", "绑定Service失败: ${e.message}", e)
                }
            } else {
                Log.e("BluetoothManagerUtil", "Service未在Manifest中声明")
            }
        }
    }

    // 解绑Service
    fun unbindService() {
        if (isBound) {
            context.unbindService(serviceConnection)
            isBound = false
        }
    }

    // 获取当前蓝牙状态
    fun getBluetoothState(): Int {
        return bluetoothService?.getBluetoothState()?: BluetoothAdapter.STATE_OFF
    }

    // 代理方法：连接设备
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun connectDevice(device: BluetoothDevice) {
        bluetoothService?.connectDevice(device)
    }

    fun senDataHelper(str:String) {
        var tempText:String = ""
        if (str.subSequence(0, 1) === "/") {
            tempText = str + "\r" + "\n"
        } else if (str.length > 4 && str.substring(0, 4) === "*/PA") {
            tempText = str
        } else {
            tempText = str + "\r"
        }
    }

    // 向客户端发送数据
    fun sendDataByClient(device: BluetoothDevice, data: ByteArray) {
        bluetoothService?.sendDataToClient(device, data)
    }


    // 代理方法：断开连接
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun disconnectDevice(device: BluetoothDevice) {
        bluetoothService?.disconnectDevice(device)
    }

    fun disAllConnectedDevice():Boolean? {
        return bluetoothService?.disconnectAllDevices()
    }

    // 代理方法：发送数据
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun sendData(device: BluetoothDevice, data: ByteArray) {
        bluetoothService?.sendData(device, data)
    }

    // 代理方法：获取已连接设备列表1
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun getConnectedDevices(): List<BluetoothDevice> {
        return bluetoothService?.getConnectedDevices() ?: emptyList()
    }

    //  代理方法：初始化时候判断是否有连接
    suspend fun isInitDeviceConnected():String? {
        return bluetoothService?.isInitDeviceConnected()
    }

    // 代理方法：获取已连接设备列表2
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun getConnectedDevices2(): List<BluetoothDevice> {
        return bluetoothService?.getConnectedDevices2() ?: emptyList()
    }

    fun isBluetoothConnected():Boolean {
        if (null  != getConnectedDevices2() && getConnectedDevices2().size>0 ) {
            return true
        } else {
            return false
        }
    }

    // 代理方法：获取已配对设备列表
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    private fun getPairedDevices(callback: (MutableList<BluetoothDevice>) -> Unit): Unit? {
        return bluetoothService?.getPairedDevices(callback)
    }

    // 代理方法：开始搜索设备
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    private fun startDiscovery(callback: (MutableList<BluetoothDevice>) -> Unit) {
        bluetoothService?.startDiscovery(callback)
    }

    // 代理方法：停止搜索设备
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    private fun stopDiscovery(callback: (MutableList<BluetoothDevice>) -> Unit) {
        bluetoothService?.stopDiscovery(callback)
    }

    // 注册回调
    fun registerCallback(callback: BluetoothService.ConnectionCallback) {
        bluetoothService?.registerCallback(callback)
    }

    // 注销回调
    fun unregisterCallback(callback: BluetoothService.ConnectionCallback) {
        bluetoothService?.unregisterCallback(callback)
    }

    // 设置回调
    fun setScanCallback(callback: (List<BluetoothDevice>) -> Unit) {
        this.scanCallback = callback
    }

    fun setPairedCallback(callback: (List<BluetoothDevice>) -> Unit) {
        this.pairedDevicesCallback = callback
    }

    // 检查蓝牙是否启用
    fun isBluetoothEnabled(): Boolean {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        return bluetoothAdapter != null && bluetoothAdapter.isEnabled
    }

    // 启用蓝牙
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun enableBluetooth(activity: Activity, requestCode: Int) {
        if (!isBluetoothEnabled()) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            activity.startActivityForResult(enableBtIntent, requestCode)
        } else {
            startScan()
        }
    }

    // 启动扫描（仅经典蓝牙）
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun startScan() {

        Log.i("BluetoothService", "开始扫描startScan")
        startDiscovery(
            callback = {

                Log.i("BluetoothService", "扫描回调的设备总数是:${it.size}")
                scannedDevices.clear()
                scannedDevices.addAll(it)
                Log.i("BluetoothService", "扫描回调scannedDevices设备总数是:${scannedDevices.size}")
                applyDeviceFilter()
                Log.i("BluetoothService", "扫描回调的经过过滤后scannedDevices设备总数是:${scannedDevices.size}")
                debounceNotifyScanResults()
            }
        )
    }

    // 停止扫描
    @RequiresPermission(Manifest.permission.BLUETOOTH_SCAN)
    fun stopScan() {
        stopDiscovery(
            callback = {
                scannedDevices.clear()
                scannedDevices.addAll(it)
                applyDeviceFilter()
                debounceNotifyScanResults()
            }
        )
    }

    // 禁用蓝牙
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun disableBluetooth(activity: Activity) {
        stopScan()
        bluetoothService?.disableBluetooth {
            if (it) {
                clearDevicesAndNotify()
            } else {
                guideUserToDisableBluetoothManually(activity)
            }
        }
    }

    // 获取系统已配对设备（后台线程处理）
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun fetchPairedDevices() {
        getPairedDevices(callback = {
            pairedDevices.clear()
            pairedDevices.addAll(it)
            notifyPairedChanges()
            applyDeviceFilter()
        })
    }

    // 设置是否显示未知设备
    fun setShowUnknownDevices(show: Boolean) {
        this.showUnknownDevices = show
        applyDeviceFilter()
    }

    // 更新配对状态
    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    fun updateBondState(device: BluetoothDevice) {
        Log.i("BluetoothService", "BluetoolsActivity 监听到配对状态 state = ${device.bondState}")
        when (device.bondState) {
            BluetoothDevice.BOND_BONDED -> {
                if (!pairedDevices.contains(device)) {
                    scannedDevices.remove(device)
                    pairedDevices.add(device)
                    handler.post {
                        notifyPairedChanges()
                        debounceNotifyScanResults()
                        applyDeviceFilter()
                    }
                }
            }

            BluetoothDevice.BOND_NONE -> {
                CentreToast.instance.showText("配对失败")
                pairedDevices.remove(device)
                handler.post {
                    notifyPairedChanges()
                    startScan()
                }

            }
        }
    }

    // 应用设备过滤（优化版）
    private fun applyDeviceFilter() {
        val oldSize = scannedDevices.size
        scannedDevices.removeIf { device ->
            (pairedDevices.contains(device)  ||
                    (!showUnknownDevices && (device.name == null || device.name.isBlank())))
        }
        if (oldSize != scannedDevices.size) {
            debounceNotifyScanResults() // 防抖通知UI
        }
    }
    // 通知扫描结果（防抖处理）
    private var lastNotifyTime = 0L
    private fun debounceNotifyScanResults() {
        if (System.currentTimeMillis() - lastNotifyTime > 300) { // 300ms防抖
            lastNotifyTime = System.currentTimeMillis()
            scanCallback?.invoke(scannedDevices)
//            scanCallback?.invoke(scannedDevices.filter { isValidDevice(it) })
        }
    }
    // 判断设备是否为有
    // 效设备
    private fun isValidDevice(device: BluetoothDevice): Boolean {
        Log.i("BluetoothService", "isValidDevice device = ${device.name}")
        return showUnknownDevices || !(device.name == null || device.name.isBlank())
    }
    // 引导用户手动禁用蓝牙
    private fun guideUserToDisableBluetoothManually(activity: Activity) {
        val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
        activity.startActivity(intent)
        CentreToast.instance.showText("请手动关闭蓝牙")

    }
    // 通知连接状态变化
    private fun notifyPairedChanges() {
        pairedDevicesCallback?.invoke(pairedDevices)
    }
    // 清空设备列表并通知UI
    private fun clearDevicesAndNotify() {
        scannedDevices.clear()
        pairedDevices.clear()
        debounceNotifyScanResults()
        notifyPairedChanges()
    }










}